<template>
  <div id="detail">
    <detail-nav-bar ref="nav" class="detail-nav" @titleClick="titleClick"></detail-nav-bar>
    <scroll class="content" ref="scroll" :probeType="3" @scroll="contentScroll">
      <detail-swiper :topImages="topImages"></detail-swiper>
      <detail-base-info :goods="goods"></detail-base-info>
      <detail-shop-info :shop="shop"></detail-shop-info>
      <detail-goods-info :detailInfo="detailInfo" @imageLoad="imageLoad"></detail-goods-info>
      <detail-param-info ref="param" :paramInfo="paramInfo"></detail-param-info>
      <detail-comment-info ref="comment" :commentInfo="commentInfo"></detail-comment-info>
      <goods-list ref="recommend" :goods="recommends"></goods-list>
    </scroll>
    <detail-bottom-bar @addCart="addToCart"></detail-bottom-bar>
    <back-top @click.native="backTop" v-show="isShowBackTop"></back-top>
  </div>
</template>

<script>
  import DetailNavBar from './childrenComps/DetailNavBar.vue'
  import DetailSwiper from './childrenComps/DetailSwiper.vue'
  import DetailBaseInfo from './childrenComps/DetailBaseInfo.vue'
  import DetailShopInfo from './childrenComps/DetailShopInfo.vue'
  import DetailGoodsInfo from './childrenComps/DetailGoodsInfo.vue'
  import DetailParamInfo from './childrenComps/DetailParamInfo.vue'
  import DetailCommentInfo from './childrenComps/DetailCommentInfo.vue'
  import GoodsList from 'components/content/goods/GoodsList'
  import DetailBottomBar from './childrenComps/DetailBottomBar.vue'

  import Scroll from 'components/common/scroll/Scroll'

  import { getDetail, getRecommend, Goods, Shop, GoodsParam} from 'network/detail.js'
  import { itemListenerMixin, backTopMixin } from 'common/mixin.js'
  import { debounce } from 'common/utils.js'
  import { mapActions } from 'vuex'

  export default {
    name: 'Detail',
    mixins: [itemListenerMixin,backTopMixin],
    data() {
      return {
        iid: null,
        topImages: [],
        goods: {},
        shop: {},
        detailInfo: {},
        paramInfo: {},
        commentInfo: {},
        recommends: [],
        itemImgListener: null,
        themeTopYs: [],
        getThemeTopY: null,
        currentIndex: 0
      }
    },
    components: {
      DetailNavBar,
      DetailSwiper,
      DetailBaseInfo,
      DetailShopInfo,
      DetailGoodsInfo,
      DetailParamInfo,
      DetailCommentInfo,
      DetailBottomBar,
      GoodsList,
      Scroll,
    },
    created() {
      // 1.保存传入的iid
      this.iid = this.$route.params.iid
      // console.log(this.iid);

      // 2.根据iid请求详情数据
      getDetail(this.iid).then(res => {
        // 1.获取顶部轮播图的图片
        // console.log(res);
        // 为了避免重复书写，定义一个变量
        const data = res.data.result;
        this.topImages = data.itemInfo.topImages;
        // console.log(this.topImages);

        // 2.获取商品信息
        this.goods = new Goods(data.itemInfo,data.columns,data.shopInfo.services);

        // 3.创建店铺信息
        this.shop = new Shop(data.shopInfo);

        // 4.保存商品的详细信息
        this.detailInfo = data.detailInfo;

        // 5.保存商品的参数信息
        this.paramInfo = new GoodsParam(data.itemParams.info,data.itemParams.rule);

        // 6.取出评论信息
        if(data.rate.cRate !== 0){
          this.commentInfo = data.rate.list[0]
        }

        // 7.给themeTopYs赋值
        // this.$nextTick 下一帧，因为页面渲染是异步进行的
        // 当创建好时，效果可能还没渲染好，需要等DOM渲染好才可以获取真实的offsetTop值
        // mounted是挂载，但是挂载好并不意味着就渲染好了

        // 但是，这里还是会出错，根据最新的数据，对应的DOM是已经被渲染出来
        // 但是图片依然是没有加载完的（目前获取到的offsetTop是不包含其中的图片的）
        // this.$nextTick(()=>{
        //   this.themeTopYs.push(0);
        //   this.themeTopYs.push(this.$refs.param.$el.offsetTop);
        //   this.themeTopYs.push(this.$refs.comment.$el.offsetTop);
        //   this.themeTopYs.push(this.$refs.recommend.$el.offsetTop);
        //   console.log(this.themeTopYs);
        // })

        this.getThemeTopY = debounce(()=>{
          this.themeTopYs.push(0);
          this.themeTopYs.push(this.$refs.param.$el.offsetTop);
          this.themeTopYs.push(this.$refs.comment.$el.offsetTop);
          this.themeTopYs.push(this.$refs.recommend.$el.offsetTop);
          this.themeTopYs.push(Number.MAX_VALUE);
          // console.log(this.themeTopYs);
        },100)
      })

      // 3.请求推荐数据
      getRecommend().then(res=>{
        // console.log(res);
        this.recommends = res.data.data.list
      })
    },
    // 因为keep-alive中exclude="Detail"，所以没有deactivated，应为destroyed
    destroyed(){
      // 取消事件监听处理
      this.$bus.$off('itemImageLoad',this.itemImgListener)
    },
    methods: {
      // 添加actions映射关系
      ...mapActions(['addCart']),
      // 监听商品详细图片加载完成后的刷新
      imageLoad(){
        this.$refs.scroll.refresh()
        this.getThemeTopY()
      },

      // 导航栏的点击滚动效果
      titleClick(index){
        this.$refs.scroll.scrollTo(0,-this.themeTopYs[index],300);
      },

      // 滚动时导航栏的切换
      contentScroll(position){
        // 1.获取y值
        const positionY = -position.y

        // 2.positionY和主题中值进行对比
        const length = this.themeTopYs.length
        // for(let i = 0; i<length; i++){
        //   // this.currentIndex !== i 防止频繁调用
        //   if ( this.currentIndex !== i && 
        //       ( (i<length-1 && positionY >= this.themeTopYs[i] && positionY < this.themeTopYs[i+1]) ||
        //       (i === length -1) && positionY >= this.themeTopYs[i] )){
        //     this.currentIndex = i;
        //     // $el是Dom元素，$refs是访问子组件
        //     this.$refs.nav.currentIndex = this.currentIndex;
        //   }
        // }
        for(let i=0; i < length-1; i++){
        // 这样都在区间中对比
        if( (this.currentIndex !== i) && (i<length-1 && positionY >= this.themeTopYs[i] && positionY < this.themeTopYs[i+1])){
            this.currentIndex = i;
            this.$refs.nav.currentIndex = this.currentIndex;
          }
        }

        // 3.是否显示回到顶部按钮,这里做了混入的抽离
        this.listenShowBackTop(position)
      },

      // 添加到购物车
      addToCart(){
        // 1.获取购物车需要的商品信息
        const product = {};
        product.images = this.topImages[0];
        product.title = this.goods.title;
        product.desc = this.goods.desc;
        product.price = this.goods.realPrice;
        product.iid = this.iid;

        // 2.添加到购物车
        // this.$store.commit('addCart',product); //mutations
        // console.log(this.goods);
        // this.$store.dispatch('addCart',product).then(res => {
        //   console.log(res);
        // })
        // 通过mapActions
        this.addCart(product).then(res => {
          // console.log(res);
          this.$toast.show(res,2000);
        })
      }
    }
  }
</script>

<style scoped>
  #detail{
    position: relative;
    z-index: 9;
    background-color: #fff;
    height: 100vh;
  }

  .detail-nav{
    position: relative;
    z-index: 9;
    background-color: #fff;
  }

  /* 给content添加高度 */
  .content{
    /* 这里的100%是相对于父元素的，所以要在#detail中添加高度100vh 
       这里的calc中减号两遍记得加空格
    */
    height: calc(100% - 44px - 49px);
  }
</style>